package com.curator.component;

import cn.hutool.core.exceptions.ExceptionUtil;
import cn.hutool.core.io.file.FileReader;
import cn.hutool.core.io.file.FileWriter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * Mysql 安装策略
 *
 * @author Jun
 * @date 2024/12/4
 */
public class ComponentInstallMysql extends AbstractComponentInstall {

    public static final Logger LOGGER = LoggerFactory.getLogger(ComponentInstallMysql.class);

    @Override
    public String componentName() {
        return "Mysql";
    }

    @Override
    public void componentInstall(InputStream inputStream, boolean runScript) {
        super.componentInstall(inputStream, false);
        try {
            String myIni = getFilePath(componentName(), "\\my.ini");
            updateIni(myIni);
            String myTempIni = getFilePath(componentName(), "\\my-temp.ini");
            updateIni(myTempIni);
            // 执行安装脚本
             super.scriptInstall();
        } catch (Exception e) {
            LOGGER.error("{} 配置出现异常 {}", componentName(), ExceptionUtil.stacktraceToString(e));
        }
    }

    public void updateIni(String destFile) {
        // 读取文件内容
        FileReader fileReader = new FileReader(destFile);
        List<String> lines = fileReader.readLines();
        // 修改文件内容
        List<String> modifiedLines = new ArrayList<>();
        for (String line : lines) {
            // 根据需要修改这里的条件和操作
            if (line.contains("basedir")) {
                line = "basedir = " + getFilePath(componentName(), "");
            } else if (line.contains("datadir")) {
                line = "datadir = " + getFilePath(componentName(), "\\data");
            } else if (line.contains("slow_query_log_file")) {
                line = "slow_query_log_file = " + getFilePath(componentName(), "\\data\\query_slow.log");
            } else if (line.contains("innodb_data_home_dir")) {
                line = "innodb_data_home_dir = " + getFilePath(componentName(), "\\data");
            } else if (line.contains("innodb_log_group_home_dir")) {
                line = "innodb_log_group_home_dir = " + getFilePath(componentName(), "\\data");
            }
            modifiedLines.add(line);
        }
        FileWriter fileWriter = new FileWriter(destFile);
        // 写入修改后的内容
        fileWriter.writeLines(modifiedLines);
    }
}
